package com.gh.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gh.entity.*;
import com.gh.enums.BorrowAuthEnum;
import com.gh.enums.BorrowerStatusEnum;
import com.gh.enums.IntegralEnum;
import com.gh.mapper.*;
import com.gh.service.BorrowerService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gh.vo.BorrowerApprovalVo;
import com.gh.vo.BorrowerAttachVo;
import com.gh.vo.BorrowerDetailVo;
import com.gh.vo.BorrowerVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 借款人 服务实现类
 * </p>
 *
 * @author Eric
 * @since 2021-09-06
 */
@Service
public class BorrowerServiceImpl extends ServiceImpl<BorrowerMapper, Borrower> implements BorrowerService {

    @Autowired
    private UserInfoMapper userInfoMapper;

    @Autowired
    private BorrowerAttachMapper borrowerAttachMapper;

    @Autowired
    private DictMapper dictMapper;

    @Autowired
    private UserIntegralMapper userIntegralMapper;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveBorrowerVoByUserId(BorrowerVo borrowerVo, Long userId) {
        //获取用户基本信息
        UserInfo userInfo = userInfoMapper.selectById(userId);
        //保存借款人信息
        Borrower borrower = new Borrower();
        BeanUtils.copyProperties(borrowerVo, borrower);
        borrower.setUserId(userId);
        borrower.setName(userInfo.getName());
        borrower.setIdCard(userInfo.getIdCard());
        borrower.setMobile(userInfo.getMobile());
        borrower.setStatus(BorrowerStatusEnum.AUTH_RUN.getStatus());
        baseMapper.insert(borrower);
        //保存附件
        borrowerVo.getBorrowerAttachList().forEach(borrowerAttach -> {
            borrowerAttach.setBorrowerId(userId);
            borrowerAttachMapper.insert(borrowerAttach);
        });
        //更新userInfo中的借款人认证状态
        userInfo.setBorrowAuthStatus(BorrowAuthEnum.AUTH_RUN.getStatus());
        userInfoMapper.updateById(userInfo);
    }

    @Override
    public Integer getBorrowerStatus(Long userId) {
        LambdaQueryWrapper<Borrower> borrowerLambdaQueryWrapper = new LambdaQueryWrapper<>();
        borrowerLambdaQueryWrapper.eq(Borrower::getUserId, userId);
        List<Borrower> borrowerList = baseMapper.selectList(borrowerLambdaQueryWrapper);
        if (borrowerList.size() == 0) {
            return BorrowerStatusEnum.NO_AUTH.getStatus();
        }
        Integer status = borrowerList.get(0).getStatus();
        return status;
    }

    @Override
    public IPage<Borrower> listPage(Page<Borrower> pageParam, String keyword) {
        LambdaQueryWrapper<Borrower> borrowerLambdaQueryWrapper = new LambdaQueryWrapper<>();
        if (StringUtils.isNotBlank(keyword)) {
            borrowerLambdaQueryWrapper.like(Borrower::getName, keyword)
                    .or().eq(Borrower::getMobile, keyword)
                    .or().eq(Borrower::getIdCard, keyword)
                    .orderByDesc(Borrower::getCreateTime);
        }
        Page<Borrower> borrowerPage = baseMapper.selectPage(pageParam, borrowerLambdaQueryWrapper);
        return borrowerPage;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public BorrowerDetailVo getBorrowerDetailVoById(Long id) {
        //创建组装返回对象
        BorrowerDetailVo borrowerDetailVo = new BorrowerDetailVo();
        //获取借款人信息
        Borrower borrower = baseMapper.selectById(id);
        //填充基本借款人信息
        BeanUtils.copyProperties(borrower, borrowerDetailVo);
        //婚否
        borrowerDetailVo.setMarry(borrower.getMarry() ? "是" : "否");
        //性别
        borrowerDetailVo.setSex(borrower.getSex() == 1 ? "男" : "女");
        //获取下拉列表的真实值
        String education = this.findDictByDictCodeAndValue("education", borrower.getEducation());
        String industry = this.findDictByDictCodeAndValue("industry", borrower.getIndustry());
        String income = this.findDictByDictCodeAndValue("income", borrower.getIncome());
        String returnSource = this.findDictByDictCodeAndValue("returnSource", borrower.getReturnSource());
        String relation = this.findDictByDictCodeAndValue("relation", borrower.getContactsRelation());
        //下拉列表
        borrowerDetailVo.setEducation(education);
        borrowerDetailVo.setIndustry(industry);
        borrowerDetailVo.setIncome(income);
        borrowerDetailVo.setReturnSource(returnSource);
        borrowerDetailVo.setContactsRelation(relation);
        //审批状态
        String status = BorrowerStatusEnum.getMsgByStatus(borrower.getStatus());
        borrowerDetailVo.setStatus(status);
        //组装附件信息
        LambdaQueryWrapper<BorrowerAttach> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(BorrowerAttach::getBorrowerId, borrower.getUserId());
        List<BorrowerAttach> borrowerAttachList = borrowerAttachMapper.selectList(lambdaQueryWrapper);
        List<BorrowerAttachVo> borrowerAttachVoList = new ArrayList<>();
        borrowerAttachList.forEach(borrowerAttach -> {
            BorrowerAttachVo borrowerAttachVo = new BorrowerAttachVo();
            BeanUtils.copyProperties(borrowerAttach, borrowerAttachVo);
            borrowerAttachVoList.add(borrowerAttachVo);
        });
        borrowerDetailVo.setBorrowerAttachVoList(borrowerAttachVoList);
        return borrowerDetailVo;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void approval(BorrowerApprovalVo borrowerApprovalVo) {
        //获取借款额度申请id
        Long borrowerId = borrowerApprovalVo.getBorrowerId();
        //获取借款额度申请对象
        Borrower borrower = baseMapper.selectById(borrowerId);
        //设置审核状态
        borrower.setStatus(borrowerApprovalVo.getStatus());
        baseMapper.updateById(borrower);
        //获取用户id
        Long userId = borrower.getUserId();
        //获取用户对象
        UserInfo userInfo = userInfoMapper.selectById(userId);
        //获取用户的原始积分
        Integer integral = userInfo.getIntegral();
        //计算积分
        UserIntegral userIntegral = new UserIntegral();
        userIntegral.setUserId(userId);
        userIntegral.setIntegral(borrowerApprovalVo.getInfoIntegral());
        userIntegral.setContent(IntegralEnum.BORROWER_INFO.getMsg());
        userIntegralMapper.insert(userIntegral);
        int currentIntegral = integral + borrowerApprovalVo.getInfoIntegral();
        //身份信息
        if (borrowerApprovalVo.getIsIdCardOk()) {
            userIntegral = new UserIntegral();
            userIntegral.setUserId(userId);
            userIntegral.setIntegral(IntegralEnum.BORROWER_IDCARD.getIntegral());
            userIntegral.setContent(IntegralEnum.BORROWER_IDCARD.getMsg());
            userIntegralMapper.insert(userIntegral);
            currentIntegral += IntegralEnum.BORROWER_IDCARD.getIntegral();
        }
        //房产信息
        if (borrowerApprovalVo.getIsHouseOk()) {
            userIntegral = new UserIntegral();
            userIntegral.setUserId(userId);
            userIntegral.setIntegral(IntegralEnum.BORROWER_HOUSE.getIntegral());
            userIntegral.setContent(IntegralEnum.BORROWER_HOUSE.getMsg());
            userIntegralMapper.insert(userIntegral);
            currentIntegral += IntegralEnum.BORROWER_HOUSE.getIntegral();
        }
        //车辆信息
        if (borrowerApprovalVo.getIsIdCardOk()) {
            userIntegral = new UserIntegral();
            userIntegral.setUserId(userId);
            userIntegral.setIntegral(IntegralEnum.BORROWER_CAR.getIntegral());
            userIntegral.setContent(IntegralEnum.BORROWER_CAR.getMsg());
            userIntegralMapper.insert(userIntegral);
            currentIntegral += IntegralEnum.BORROWER_CAR.getIntegral();
        }
        //设置用户积分
        userInfo.setIntegral(currentIntegral);
        //修改审核状态
        userInfo.setBorrowAuthStatus(borrowerApprovalVo.getStatus());
        userInfoMapper.updateById(userInfo);
    }

    /**
     * 通过dictcode和value查询name
     *
     * @param dictCode
     * @param value
     * @return
     */
    private String findDictByDictCodeAndValue(String dictCode, Integer value) {
        LambdaQueryWrapper<Dict> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Dict::getDictCode, dictCode);
        Dict parentDict = dictMapper.selectOne(lambdaQueryWrapper);
        if (parentDict == null) {
            return "";
        }
        lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Dict::getParentId, parentDict.getId());
        lambdaQueryWrapper.eq(Dict::getValue, value);
        Dict dict = dictMapper.selectOne(lambdaQueryWrapper);
        if (dict == null) {
            return "";
        }
        return dict.getName();
    }

}
